package website.seamonster.ethegg.service.background;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import website.seamonster.ethegg.conf.SystemConfig;
import website.seamonster.ethegg.dataobject.*;
import website.seamonster.ethegg.enums.EggStatusEnum;
import website.seamonster.ethegg.enums.ResultEnum;
import website.seamonster.ethegg.exception.EthException;
import website.seamonster.ethegg.repository.ChickenRepository;
import website.seamonster.ethegg.repository.EggRepository;
import website.seamonster.ethegg.repository.TransactionRepository;
import website.seamonster.ethegg.repository.UserRepository;
import website.seamonster.ethegg.schedule.ScheduleManager;
import website.seamonster.ethegg.service.AccountService;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by 罗海量
 * 2018-07-18 01:03
 */
@lombok.extern.slf4j.Slf4j
@Service
public class BuyEggService {
    @Autowired
    private TransactionRepository txRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ChickenRepository chickenRepository;
    @Autowired
    private EggRepository eggRepository;
    @Autowired
    private AccountService accountService;
    @Autowired
    private TransactionService txService;
    /**
     * 购买一只蛋
     * @param txReq
     */
    @Transactional
    public void buyEgg(TxReq txReq){

    }

    /**
     * 用户购买1只蛋
     * @param txReqId
     * @param buyerUserId
     * @param prCode
     * @param prUserId
     */
    @org.springframework.transaction.annotation.Transactional
    public void buyEgg(long txReqId, String buyerUserId, String prCode, String prUserId){
        //判断用户孵化圈是否足够
        User u = userRepository.findOne(buyerUserId);
        int chickenCount = chickenRepository.getCountByUserId(buyerUserId);
        if (u.getMaxHatch() <= chickenCount){
            throw new EthException(ResultEnum.HATCH_NO_ENOUGH);
        }

        //寻找合适的蛋，修改蛋资料
        Egg eggToBuy = eggRepository.findEggToBuy(buyerUserId);
        eggToBuy.setEggStatus(EggStatusEnum.TRADING.getCode());
//        eggToBuy.setUserId(buyerUserId);

        //蛋的卖家Id
        String sellerUserId = eggToBuy.getUserId();
        /*
        //蛋的母鸡ID
        Long chickenId = eggToBuy.getChickenId();
        */

        //创建1条交易记录
        Transaction tx = new Transaction();
        tx.setBuyId(buyerUserId);
        tx.setEggId(eggToBuy.getId());
        tx.setSellId(sellerUserId);
        BigDecimal price = eggToBuy.getPrice();
        tx.setBuyExpense(price);
        tx.setTxReqId(txReqId);
        tx.setSellIncome(price.multiply(SystemConfig.SELLER_INCOME_PERCENTAGE));
        if (prCode == null) {
            tx.setServiceFee(price.multiply(SystemConfig.SERVICE_FEE_PERCENTAGE));
        }else{
            tx.setServiceFee(price.multiply(SystemConfig.SERVICE_FEE_PR_PERCENTAGE));
            tx.setPrCode(prCode);
            tx.setPrUserId(prUserId);
            tx.setPrIncome(price.multiply(SystemConfig.PR_INCOME_PERCENTAGE));
        }
        Transaction txUpdate = txRepository.save(tx);
        eggRepository.save(eggToBuy);

        //调用支付接口（按理说应该做成异步回调）
        this.pay(buyerUserId, sellerUserId, prUserId, tx);
        txService.doSuccessTransaction(txUpdate);
    }

    /**
     * 四方交易
     * (TODO 1.如果卖家是系统本身，应该把"卖家收70%"和"系统收的手续费"合为一个交易 2.最终应该调整成异步， 3.对接以太坊  )
     * @param buyerUserId
     * @param sellerUserId
     * @param prUserId
     * @param tx
     */
    @Transactional
    public void pay(String buyerUserId, String sellerUserId, String prUserId, Transaction tx){
        //1 购买用户扣钱
        accountService.decrease(buyerUserId, tx.getBuyExpense());
        //2 卖蛋用户收钱70%
        accountService.increase(sellerUserId, tx.getSellIncome());
        //3 有推广码，系统收钱22%，推广用户收钱8%； 无推广码，系统收钱30%
        accountService.increase(SystemConfig.SYS_USER_ID, tx.getServiceFee());
        if (prUserId != null) {
            accountService.increase(prUserId, tx.getPrIncome());
        }
    }

    /*
    @Transactional
    protected void eggToChicken(Long eggId, String userId){
        eggRepository.born(eggId);
        Chicken chicken = new Chicken();
        chicken.setAlive(true);
        chicken.setBornNum(0);
        chicken.setUserId(userId);
        chickenRepository.save(chicken);
    }
    */
}
